package com.berchen.offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 不分行从上往下打印出二叉树的每个节点，同层节点从左至右打印。例如输入{8,6,10,#,#,2,1}，如以下图中的示例二叉树，则依次打印8,6,10,2,1(空节点不打印，跳过)，请你将打印的结果存放到一个数组里面，返回。
 */
public class Test03 {
    public static void main(String[] args){
        TreeNode root=new TreeNode(8);
        TreeNode node6=new TreeNode(6);
        TreeNode node10=new TreeNode(10);
        TreeNode node2=new TreeNode(2);
        TreeNode node1=new TreeNode(1);
        node10.left=node2;
        node10.right=node1;
        root.left=node6;
        root.right=node10;
        Test03 test03 = new Test03();
        ArrayList<Integer> integers = test03.PrintFromTopToBottom(root);
        System.out.println(integers);
    }
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {

        ArrayList<Integer> result=new ArrayList<>();
        if(root==null){

            return result;
        }
        Queue<TreeNode> queue=new ArrayDeque<>();
        queue.add(root);
        result.add(root.val);
        diGui(result,queue);
        return result;
    }
    public void diGui(ArrayList<Integer> result,Queue<TreeNode> queue){

        if(queue.size()!=0){
            TreeNode node = queue.poll();
            TreeNode left=node.left;
            TreeNode right=node.right;

            if(left!=null) {
                result.add(left.val);
                queue.add(left);
            }
            if(right!=null) {
                result.add(right.val);
                queue.add(right);
            }
            diGui(result, queue);
        }
    }
}
